﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LeafCore.Commons.Utils
{
    public static class StringHelper
    {

        /// <summary>
        /// 转换成json字符串
        /// </summary>
        /// <param name="obj">数据源</param>
        /// <param name="setting">Json设置</param>
        /// <returns></returns>
        public static string ToJsonString(this object obj, JsonSerializerSettings setting = null)
        {
            if (obj == null)
            {
                return string.Empty;
            }

            return JsonConvert.SerializeObject(obj, setting);
        }

        /// <summary>
        ///  判断是否为null，null或0长度都返回true
        /// </summary>
        /// <typeparam name="T">数据类型</typeparam>
        /// <param name="value">数据</param>
        /// <returns></returns>
        public static bool IsNullOrEmpty<T>(this T value) where T : class
        {
            if (value == null)
            {
                return true;
            }

            IEnumerator enumerator = (value as IEnumerable)?.GetEnumerator();
            if (enumerator == null)
            {
                return false;
            }

            bool flag = !enumerator.MoveNext();
            if (flag)
            {
                return true;
            }

            return flag;
        }

        /// <summary>
        /// Json字符串转实体对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        public static T? ToEntity<T>(this string jsonStr) where T : class
        {
            if (string.IsNullOrEmpty(jsonStr))
                return null;

            return JsonConvert.DeserializeObject<T>(jsonStr);
        }

        /// <summary>
        /// 字符串转换UTF8字节数据
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static byte[] ToUTF8Bytes(this string source)
        {
            return Encoding.UTF8.GetBytes(source);
        }
    }
}
